const app = getApp();
const utils = require('../../utils/util.js');
const pay = require('../../utils/pay.js');
var WxParse = require('../../../wxParse/wxParse.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 外卖订单新版
    seltoid: '',//商家uid
    pid: 0, //商品PID
    title: '', //商品名
    state: 4, //0代表上架，1代表下架, 3已拒绝，4审核中
    cateid: 375, //195其他分类(单品), 375 代金券商品, 376 套餐商品
    bprice: '', //商品价格
    yjprice: '',//佣金价格
    videoSrc: "", //视频
    selType: 0,//购买限制;0无限制，1限购一份，2每天限购一份
    date: '', // 有效期
    nowData: '',//当天日期
    sendStartDate: '',
    sendEndDate: '',
    useStartDate: '',
    useEndDate: '',
    cutPoicy: '', //优惠政策
    count: '', //数量
    description: `1、使用时间: 2020年4月29日-6月29日，所有日期通用
2、适用门]店:梅林店、南头店、蛇口店
3、适用范围:酒水、茶位费除外，全场通用
4、门店营业时间可用，无需预约，消费高峰期可能需要等位
5、每人限购5张，满200元可用1张，满400元可用2张，以此类推，规则内可无限叠加使用
6、本券不兑现、不找零，不可与其他优惠同享
7、仅限堂食，不提供餐前外带
8、发票、酒水饮料、停车位收费标准等问题请详询商家，以商家反馈为准
9、如部分菜品因时令或其他不可抗因素导致无法提供，商家会用等价菜品替换，具体事宜请与商家协商
10、本券为限时抢购商品，一经抢购，不支持退款，请谨慎抢购!（本单支持转赠）
11、商家门店地址：  
12、商家预约电话：
13、咨询投诉电话：0755-83650822（玖玖客总部客服电话）`, //产品描述
    detailPics: [], //商品头图集合
    pics: [], //头图
    productPic: [], //详情图
    showDetailPics: [],//渲染头图
    showProductPic: [],//渲染详情图
    showLicense: '',//渲染营业执照
    top: 70,
    showPoste: false,
    salecount: 0,
    refuse: '',
    limitCount: '',//限购几份
    totalMoney: 0,//押金金额
    orderState: 0,//申请押金退款状态
    showDialog: false,
    canTuikuan: false,
    applySuccess: false,
    imgsrc: '',
    isBackEditor: false,//是否是在企动后台编辑
    isWxStore: false,
    isWxCard: 0,//0普通代金券1微信代金券
    coverImg: '',//微信卡券封面图
    
    marketPrice: 0, //市场价  
    provinces: [],
    citys: [],
    districts: [],
    regionName: '',
    regions:[],    //选中的区域
    navTitle: '产品'    //导航标题
  },

  showTuikuan: function () {
    let useEndDate = this.data.useEndDate;
    let newTime = useEndDate + ' 23:59:59';
    let nowTime = new Date();
    newTime = new Date(Date.parse(newTime.replace(/-/g, "/")));
    if (newTime > nowTime) {
      this.setData({
        showDialog: true,
        canTuikuan: false
      })
      return;
    } else {
      this.setData({
        showDialog: true,
        canTuikuan: true
      })
    }
  },

  closeTuikuan: function () {
    this.setData({
      showDialog: false,
      applySuccess: false
    })
  },

  //获取微信商户
  getWxStore: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/WxStore/GetWxStoreByUid?uid=' + app.globalData.userInfo.Uid,
      success: function (res) {
        if (res.data.Data) {
          that.setData({
            isWxStore: true
          })
        }
      }
    })
  },


  // 申请退押金
  toApplyTuikuan: function () {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/OrderAfter/ApplyRefundDeposit',
      data: {
        pid: that.data.pid,
        uid: app.globalData.userInfo.Uid
      },
      method: 'POST',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            applySuccess: true
          })
          that.getGoodDetails(that.data.pid);
        } else { 
          that.showModal(res.data.Message);
        }
      }
    })
  },

  // 购买限制
  modelUpdate: function (e) {
    let selType = e.currentTarget.dataset.seltype
    this.setData({
      selType: selType
    })
  },
  wxcouponUpdate: function (e) {
    let isWxCard = e.currentTarget.dataset.iswxcard;
    this.setData({
      isWxCard: isWxCard
    })
  },
  // 上传微信卡券封面图
  uploadCoverImage: function () {
    var that = this;
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        that.uploadwximg({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: imgs, //这里是选取的图片的地址数组
        });
      },
    })
  },

  // 单图上传
  uploadwximg: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[0],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        var str = resp.data
        var pic = JSON.parse(str);
        var coverImg = 'https://static.711688.net.cn/upload/coupondetail/' + pic.Data;
        that.setData({
          coverImg: coverImg
        })
      }
    });
  },

  offLine: function () {
    this.data.state = 1;
    this.saveProduct();
  },

  getLiense: function () {
    let that = this;
    let staffid = wx.getStorageSync('cardId');
    if (staffid) {
      wx.request({
        url: app.globalData.host + '/api/staff/GetStaffExtend?staffid=' + staffid + '&keyword=29',
        success: function (res) {
          if (res.data.Data) {
            let showLicense = '';
            if (res.data.Data.Value) {
              showLicense = utils.formatAvater(res.data.Data.Value, 'https://static.711688.net.cn/upload/coupondetail/');
            }
            that.setData({
              showLicense: showLicense
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLiense();
    this.getWxStore();
    if (options.seltoid) {
      this.setData({
        seltoid: options.seltoid
      })
    }
    if (options.pid) {
      this.getGoodDetails(options.pid);
      this.setData({
        pid: options.pid
      })
    } else {
      let nowDate = utils.getCurrentToday();
      let nowDate2 = utils.getCurrentToday();
      let sendEndDate = utils.formatTime(utils.jiaDate(nowDate, 60));
      let useEndDate = utils.formatTime(utils.jiaDate(nowDate2, 90));
      nowDate = nowDate.substr(0, 10);
      sendEndDate = sendEndDate.substr(0, 10).replace(/\//g, "-");
      useEndDate = useEndDate.substr(0, 10).replace(/\//g, "-");
      this.setData({
        nowData: nowDate,
        sendStartDate: nowDate,
        sendEndDate: sendEndDate,
        useStartDate: nowDate,
        useEndDate: useEndDate,
      })
      this.getDraft();
    }

    if (options.title) {
      this.getRegion(0,0,'');
      this.setData({
        navTitle: options.title,
        cateid: 377
      })
    }    
    setTimeout(() => {
      console.log('state',this.data.state)
    }, 1000);
  },

  onShow: function () {
    if (this.data.imgsrc) {
      let newsAvaters = [];
      newsAvaters.push(this.data.imgsrc);
      this.data.picIndex = 1;
      //这里触发图片上传的方法（头图）
      if (newsAvaters.length > 0) {
        this.uploadimg({
          url: app.globalData.host + '/api/tool/upload?operation=uploadproductimage&storeid=' + app.globalData.storeId, //这里是你图片上传的接口
          path: newsAvaters, //这里是选取的图片的地址数组
        })
      }
      this.setData({
        imgsrc: ''
      })
    }
  },
  //发布商品
  saveProduct: function () {
    let that = this;
    let price = that.getFloat(that.data.bprice);
    let yjprice = that.getFloat(that.data.yjprice);   
    //let costPrice = that.getFloat(that.data.yjprice);
    let marketPrice = that.getFloat(that.data.marketPrice);
    let cateid = that.getInt(that.data.cateid);  
    let limitCount = that.data.selType == 1 ? that.getInt(that.data.limitCount) : 0;  
    let path = '/api/store/AddUpdatePromoteProduct';    
    
    if(cateid==377 || cateid==378){     
      path = '/api/store/AddOrUpdateUserProduct';
      yjprice =  price * 0.8;
    }
    if (!that.data.title) {
      that.showToast('请输入标题'); return;
    }
    if (price < 9.9) {
      that.showToast('价格最低9.9'); return;
    }
    if (yjprice > 0 && yjprice < 9.9) {
      that.showToast('价格最低9.9'); return;
    }
    if (parseFloat(yjprice) > parseFloat(price)) {
      that.showToast('抢购价不高于价格'); return;
    } 
    if (that.data.detailPics.length == 0) {
      that.showToast('请先上传产品图片'); return;
    }
    if (that.data.detailPics.length > 6) {
      that.showToast('最多选择6张！'); return;
    }
    if (that.getInt(that.data.count)<1) {
      that.showToast('请输入库存'); return;
    }   
    if (that.data.selType == 1 && limitCount < 1) {
      that.showToast('请填写限购几份'); return;
    } 
    if(that.compareDate(that.data.sendStartDate,that.data.sendEndDate)){
      that.showModal('发放开始时间不能大于发放结束时间'); return;
    }
    if(that.compareDate(that.data.useStartDate, that.data.useEndDate)){
      that.showModal('使用开始时间不能大于使用结束时间'); return;
    }
    if(that.compareDate(that.data.sendEndDate,that.data.useEndDate)){
      that.showModal('发放结束时间不能大于使用结束时间'); return;
    }
    // 发放、使用时间
    if (that.data.isWxCard == 1) {//微信券
      let timeDiff = that.getInervalDay(that.data.sendStartDate + ' 00:00:00', that.data.sendEndDate + ' 23:59:59');
      let day = timeDiff / 1000 / 60 / 60 / 24;
      if (day > 90) {
        that.showModal('微信券有效期最长不超过90天');
        return;
      }
      let timeDiffTwo = that.getInervalDay(that.data.useStartDate + ' 00:00:00', that.data.useEndDate + ' 23:59:59');
      let dayTwo = timeDiffTwo / 1000 / 60 / 60 / 24;
      if (dayTwo > 90) {
        that.showModal('微信券有效期最长不超过90天');
        return;
      }
    }               
   
    if(cateid == 376){
      that.data.isWxCard = 0;
    }    
  
    let data = {
      Pid: that.data.pid,
      ProductName: that.data.title,
      ShopPrice: price.toFixed(2), //价格
      // CostPrice: costPrice.toFixed(2),  //成本价,云加盟用到
      BrokeragePrice: yjprice.toFixed(2),//佣金价格(代金券/套餐)
      MarketPrice: marketPrice.toFixed(2),//市场价
      Description: that.data.description, //详情描述
      Images: that.data.detailPics, //头图
      Uid: app.globalData.userInfo.Uid,
      DisplayOrder: 0, //排序
      VideoSrc: that.data.videoSrc, //视频 
      ShadowPrice: that.data.cutPoicy, //优惠政策
      StoreCid: 0, //分类
      DetailPics: that.data.productPic, //产品详情图
      Stock: that.getInt(that.data.count), //库存
      State: 4, //状态 0代表上架，1代表下架,3拒绝 4提交审核中
      CateId: cateid, //195其他分类(单品), 375 代金券商品, 376 套餐商品
      OptionIds: '', //规格id, 多个逗号隔开
      BuyType: that.data.selType,//购买限制
      BuyCount: limitCount,   //限购几份
      SendStartTime: that.data.sendStartDate,
      SendEndTime: that.data.sendEndDate,
      UseStartTime: that.data.useStartDate,
      UseEndTime: that.data.useEndDate,
      IsWxCard: that.data.isWxCard,
      Regions: that.data.regions.join(',')  //指定区域, 默认全国
    };

    wx.showModal({
      title: '提示',
      content: '是否确认提交！',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({title: '提交中',mask: true})
          wx.request({
            url: app.globalData.host + path,
            method: "POST",
            data: data,
            success: function (res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                wx.removeStorageSync('productInfo');
                that.data.state = 4;
                if (res.data.Data.Oid && res.data.Data.Oid > 0) {
                  if (res.data.Data.TotalMoney > 0) {
                    pay.wxcashpay(app, res.data.Data.Oid, '/merchant/merchants/nearbyCoupon/index');
                  }
                } else {            
                  var relaunchUrl = cateid ==377 || cateid ==378 ? '../join/index' : '../nearbyCoupon/index';      
                  wx.reLaunch({url: relaunchUrl})
                }
              } else {
                that.showModal(res.data.Message);
              }
            }
          })
        }
      }
    })
  },

  // 保存草稿
  saveDraft: function () {
    let produnctInfo = {};
    produnctInfo.pid = this.data.pid;
    produnctInfo.cateid = this.data.cateid;
    produnctInfo.title = this.data.title;
    produnctInfo.bprice = this.data.bprice;
    produnctInfo.yjprice = this.data.yjprice;
    produnctInfo.description = this.data.description;
    produnctInfo.detailPics = this.data.detailPics;
    produnctInfo.showDetailPics = this.data.showDetailPics;
    produnctInfo.cutPoicy = this.data.cutPoicy;
    produnctInfo.productPic = this.data.productPic;
    produnctInfo.showProductPic = this.data.showProductPic;
    produnctInfo.count = this.data.count;
    produnctInfo.selType = this.data.selType;
    produnctInfo.limitCount = this.data.limitCount;
    produnctInfo.sendStartDate = this.data.sendStartDate;
    produnctInfo.sendEndDate = this.data.sendEndDate;
    produnctInfo.useStartDate = this.data.useStartDate;
    produnctInfo.useEndDate = this.data.useEndDate;
    wx.setStorageSync('productInfo', produnctInfo);
    wx.showToast({title: '保存成功',mask: true,duration: 1500});
  },
 //获取草稿
 getDraft: function(){
  let proInfo = wx.getStorageSync('productInfo');
  if (proInfo) {
    this.setData({
      pid: proInfo.pid,
      cateid: proInfo.cateid,
      title: proInfo.title,
      bprice: proInfo.bprice,
      yjprice: proInfo.yjprice,
      description: proInfo.description,
      detailPics: proInfo.detailPics,
      showDetailPics: proInfo.showDetailPics,
      cutPoicy: proInfo.cutPoicy,
      state: proInfo.state,
      productPic: proInfo.productPic,
      showProductPic: proInfo.showProductPic,
      count: proInfo.count,
      selType: proInfo.selType,
      limitCount: proInfo.limitCount,
      sendStartDate: proInfo.sendStartDate,
      sendEndDate: proInfo.sendEndDate,
      useStartDate: proInfo.useStartDate,
      useEndDate: proInfo.useEndDate
    })
  }
},
  // 删除产品
  deleteProduct: function () {
    var that = this;
    let pid = that.data.pid;
    let orderState = that.data.orderState;
    
    if (orderState > 100 && orderState != 200 && that.data.cateid < 377) {
      that.showModal('尚未退押金不能删除该商品');
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确认是否删除！',
      success(res) {
        if (res.confirm) {
          wx.showLoading({title: '正在删除',mask: true,})
          wx.request({
            url: app.globalData.host + "/api/Store/RecycleProductById?pids=" + pid,
            success: function (res) {
              wx.hideLoading();
              if (res.data.Code == 0) {
                wx.reLaunch({
                  url: '../nearbyCoupon/index',
                })
              } else {
                that.showModal(res.data.Message);
              }
            },
            fail: function (res) {
              that.showModal(res.data.Message);             
            }
          })
        }
      }
    })
  },
  //获取商品详情
  getGoodDetails: function (pid) {
    var that = this;
    if (pid < 1)return;
    wx.request({
      url: app.globalData.host + '/api/store/Product?pid=' + pid + '&isextend=1&isLive=1',
      success: function (res) {
        if (res.data.Code == 0) {
          let selType = 0;
          let detailPics = [];
          let product =  res.data.Data.ProductInfo;
          let extend = res.data.Data.Extend? res.data.Data.Extend : {};
          let productPic = product.DetailPics ? JSON.parse(product.DetailPics) : [];
          let showProductPic = [];
          let showDetailPics = [];
          let limitCount = 0;
          let picPath= 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/';
          if (res.data.Data.SinglePromotionInfo) {//限购一份或每天限购一份
            if (res.data.Data.SinglePromotionInfo.DayBuyCount > 0) {//每天限购一份
              selType = 2;
            } else {
              selType = 1;
              limitCount = res.data.Data.SinglePromotionInfo.AllowBuyCount;
            }
          }
          //详情图    
          for(let i = 0; i < productPic.length; i++){
            showProductPic[i] = utils.formatAvater(productPic[i], picPath);
          } 
          //头图            
          for(let i = 0; i < res.data.Data.ProductImageList.length; i++){
            let image =res.data.Data.ProductImageList[i];
            detailPics.push(image.ShowImg);
            showDetailPics.push(
              image.ShowImg.indexOf('ps') != -1 ?
              utils.formatAvaterByProHead(image.ShowImg) : 
              utils.formatAvater(image.ShowImg, picPath));
          }

          let isBackEditor = false;
          if (product.Description.indexOf('style=') != -1 || product.Description.indexOf('</p>') != -1) {
            isBackEditor = true;
          }
          that.setData({
            pid: pid,
            cateid: product.CateId,
            title: product.Name,
            bprice: product.ShopPrice,
            costPrice: product.CostPrice,
            yjprice: extend.BrokeragePrice,
            description: product.Description,
            detailPics: detailPics,
            showDetailPics: showDetailPics,
            cutPoicy: product.ShadowPrice,
            state: product.State,
            productPic: productPic ? productPic : [],
            showProductPic: showProductPic,
            count: res.data.Data.StockNumber,
            selType: selType,
            limitCount: limitCount,
            salecount: product.SaleCount,
            refuse: product.VideoSrc,
            sendStartDate: that.subData(extend.SendStartTime),
            sendEndDate: that.subData(extend.SendEndTime),
            useStartDate: that.subData(extend.UseStartTime),
            useEndDate: that.subData(extend.UseEndTime),         
            totalMoney: res.data.Data.Deposit.TotalMoney,//押金金额
            orderState: res.data.Data.Deposit.OrderState,
            isBackEditor: isBackEditor,
            regions: extend.Regions == '' ? [] : extend.Regions.split(','),   //指定区域, 默认全国
            navTitle: product.CateId == 377 || product.CateId==378 ? '项目': '产品'
          })
          WxParse.wxParse('article', 'html', product.Description, that, 5);
          
          if(product.CateId == 377 || product.CateId==378){
            that.getRegion(0,0,'');
          }   
        }
      }
    }) 
  },
 
  changeCateid: function (e) {
    let cateid = e.currentTarget.dataset.cateid;
    this.setData({
      cateid: cateid
    })
  },

  bindTitleInput: function (e) {
    this.setData({
      title: e.detail.value
    })
  },
  cancel: function () {
    wx.navigateBack({
      delta: 1
    })
  },
  bindCounts: function (e) {
    this.setData({
      count: e.detail.value
    })
  },
  //商品本店价
  bindPrice: function (e) {
    this.setData({
      bprice: e.detail.value
    })
  },
  //佣金价格
  bindYjPrice: function (e) {
    this.setData({
      yjprice: e.detail.value
    })
  },
   //市场价
   bindMarketPrice: function (e) {
    this.setData({
      marketPrice: e.detail.value
    })
  },
  // //成本价
  // bindCostPrice: function (e) {
  //   this.setData({
  //     costPrice: e.detail.value,
  //     yjprice: e.detail.value
  //   })
  // },

  // 优惠政策
  bindCutPoicy: function (e) {
    this.setData({
      cutPoicy: e.detail.value
    })
  },

  bindDescriptionInput: function (e) {
    this.setData({
      description: e.detail.value
    })
  },
  bindSendStartDate: function (e) {
    this.setData({
      sendStartDate: e.detail.value
    })
  },
  bindSendEndDate: function (e) {
    this.setData({
      sendEndDate: e.detail.value
    })
  },
  bindUseStartDate: function (e) {
    this.setData({
      useStartDate: e.detail.value
    })
  },
  bindUseEndDate: function (e) {
    this.setData({
      useEndDate: e.detail.value
    })
  },
  bindLimit: function (e) {
    this.setData({
      selType: 1,
      limitCount: e.detail.value
    })
  },
  //招商开始时间
  bindJoinStartDate: function (e) {
    this.setData({
      sendStartDate: e.detail.value,
      useStartDate: e.detail.value,
    })
  },
  //招商截止时间
  bindJoinEndDate: function (e) {
    this.setData({
      sendEndDate: e.detail.value,
      useEndDate:  e.detail.value,
    })
  },
  //监听用户滑动页面事件
  onPageScroll: function (e) {
    let top = parseInt(e.scrollTop) + 70;
    this.setData({
      top: top
    })
  },

  //调用子组件的方法生成海报
  sharePoste: function () {
    this.selectComponent('#getPoster').getAvaterInfo();
  },
  myEventListener: function (e) {
    this.setData({
      showVideo: true
    })
  },

  /**
 * 长按删除详细图片
 */
  deleteDetailPic: function (e) {
    var that = this;
    var pic = e.currentTarget.dataset.pic;
    if (pic == 1) {//头图
      var newPics = that.data.detailPics;
      let showDetailPics = that.data.showDetailPics;
      newPics.splice(e.currentTarget.dataset.index, 1);
      showDetailPics.splice(e.currentTarget.dataset.index, 1);
      that.setData({
        detailPics: newPics,
        showDetailPics: showDetailPics
      })
    } else if (pic == 2) {//详情图
      var newPics = that.data.productPic;
      let showProductPic = that.data.showProductPic;
      newPics.splice(e.currentTarget.dataset.index, 1);
      showProductPic.splice(e.currentTarget.dataset.index, 1);
      that.setData({
        productPic: newPics,
        showProductPic: showProductPic
      })
    } else if (pic == 3) {//营业执照
      var newPics = that.data.license;
      let showLicense = that.data.showLicense;
      newPics.splice(e.currentTarget.dataset.index, 1);
      showLicense.splice(e.currentTarget.dataset.index, 1);
      that.setData({
        license: newPics,
        showLicense: showLicense
      })
    } else if (pic == 4) {//合同
      var newPics = that.data.contracts;
      let showContracts = that.data.showContracts;
      newPics.splice(e.currentTarget.dataset.index, 1);
      showContracts.splice(e.currentTarget.dataset.index, 1);
      that.setData({
        contracts: newPics,
        showContracts: showContracts
      })
    }
  },
  /**
   * 上传头图(裁剪)
   */
  uploadHeadImage: function (e) { //这里是选取图片的方法（商家轮播头图裁剪）
    var that = this;
    var detailPics = that.data.detailPics;
    if (detailPics.length >= 6) {
      that.showToast('最多选择6张！'); return;
    }
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      complete: function (res) {
        if (res.tempFilePaths) {
          wx.navigateTo({
            url: '/pages/weijieke/chooseImage/index?src=' + res.tempFilePaths[0],
          })
        }
      }
    })
  },
  /**
   * 上传详细图片
   */
  uploadDetailImage: function (e) { //这里是选取图片的方法
    var that = this;
    var detailPics = [];
    var pic = e.currentTarget.dataset.pic;
    that.setData({
      picIndex: pic
    })
    detailPics = that.data.productPic;
    var pics = [];
    if (detailPics.length >= 6 && pic != 3) {
      that.showToast('最多选择6张！'); return;
    }
     if (detailPics.length >= 1 && pic == 3) {
      that.showToast('最多选择1张！'); return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          if (pics.length < 6 - detailPics.length) {
            pics.push(imgs[i]);
          }
        }
        that.uploadimg({
          url: app.globalData.host + '/api/tool/upload?operation=saveproducteditorimage&storeid=' + app.globalData.storeId, //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        })
      },
    })
  },

  //多张图片上传(产品头图、详情图)
  uploadimg: function (data) {
    wx.showLoading({
      title: '上传中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = pic.Data;
        if (that.data.picIndex == 1) {//头图
          var detailPics = that.data.detailPics;
          detailPics.push(pic_name);
          var showDetailPics = detailPics.concat();
          for (let j = 0; j < showDetailPics.length; j++) {
            showDetailPics[j] = utils.formatAvaterByProHead(showDetailPics[j]);
          }
          that.setData({
            detailPics: detailPics,
            showDetailPics: showDetailPics
          })
        } else {
          var productPic = that.data.productPic;
          productPic.push(pic_name);
          var showProductPic = productPic.concat();
          for (let j = 0; j < showProductPic.length; j++) {
            showProductPic[j] = utils.formatAvater(showProductPic[j], 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/editor/');
          }
          that.setData({
            productPic: productPic,
            showProductPic: showProductPic
          })
        }
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    });
  },

  onShareAppMessage: function () {
    var that = this;
    var cardid = wx.getStorageSync("cardId");
    return {
      imageUrl: that.data.showDetailPics[0],
      title: that.data.title,
      path: '/pages/index/index?id=' + cardid + '&source=2' + '&pid=' + that.data.pid + '&saleUid=' + app.globalData.userInfo.Uid + '&seltoid=' + app.globalData.userInfo.Uid,
      success: function (res) {      
        that.showModal('转发成功');
      }
    }
  },
  
 //获取省、市、区
 getRegion: function (index,id,name) {
  var that = this;
  var paths=[
    '/api/Tool/ProvinceList',
    '/api/Tool/CityList?provinceId=' + id,
    '/api/Tool/CountyList?cityId=' + id
  ]
  wx.request({
    url: app.globalData.host + paths[index],
    success: function (res) {
      var data = JSON.parse(res.data.Data);          
      if(index == 0){
        that.setData({
          provinces: data,
          selProvince: '请选择省',
          selCity: '',
          selDistrict: ''
        })
      }
      if(index == 1){
        that.setData({
          citys: data,
          selProvince: name,
          selCity:'不限'
        })
      }
      if(index == 2){
        that.setData({
          districts: data,
          selCity: name,
          selDistrict:'不限'
        })
      }
    }
  })
},
// 两个日期相差的天数（传入的时间为标准时间格式）
getInervalDay: function (startDate, endDate) {
  var startDate = new Date(startDate.replace(/-/g, "/"));; //日期字符串
  var endDate = new Date(endDate.replace(/-/g, "/"));; //日期字符串
  var ms = endDate.getTime() - startDate.getTime();
  return ms;
},
//增加区域
setRgion: function(){
  var that = this;
  var name = that.data.selProvince + that.data.selCity + that.data.selDistrict;
  var regions = that.data.regions;
  if(that.data.selProvince =='' || that.data.selProvince =='请选择省'){
    that.showToast('请选择省份'); return;
  }
  regions.push(name.replace('不限',''));
  console.log(regions)
  that.setData({
    regions: regions,
    regionName: '',
    selProvince: '请选择省',
    selCity: ''
  })
},

//删除区域
delRegion: function(e){
 var index= e.currentTarget.dataset.index;
  var that = this;
  var regions = [];
  console.log(e.currentTarget.dataset)
  for(var i=0; i < that.data.regions.length;i++){
    var name = that.data.regions[i];
    if(i != index){
      regions.push(name)
    }                  
  }
  that.setData({
    regions: regions
  })
},
//省选择
bindProvince: function (e) {
  var item = this.data.provinces[e.detail.value]
  this.getRegion(1,item.id,item.name);
},
//市值选择
bindCity: function (e) {
  var that = this;
  var item = that.data.citys[e.detail.value]
  that.getRegion(2,item.id,item.name);
},  
bindCounty: function (e) {
  var that = this;
  var item = that.data.districts[e.detail.value]
  that.data.selDistrict = item.name;
  that.setRgion();
},
getFloat:function(text){
  if (text === undefined || text == '' || isNaN(text)) 
    return 0;
  return parseFloat(text);
},
getInt:function(text){
  if (text === undefined || text == '' || isNaN(text)) 
    return 0;
  return parseInt(text);
},
showToast: function(title){
  wx.showToast({title: title, icon:'none'})
},
showModal: function(content){
  wx.showModal({
    title: '提示',
    content: content,
    showCancel: false
  })
},
subData: function(time){
  return time ? time.substr(0, 10) : '';
},
//日期比较
compareDate: function(start, end){
  start+= ' 00:00:00';
  end +=  ' 23:59:59';
  let startDate = new Date(start.replace(/-/g, "/"));
  let endDate = new Date(end.replace(/-/g, "/"));
  return startDate > endDate;
}
})